<?php
/*
	Copyright © Eleanor CMS
	URL: http://eleanor-cms.ru, http://eleanor-cms.com
	E-mail: support@eleanor-cms.ru
	Developing: Alexander Sunvas*
	Interface: Rumin Sergey
	=====
	*Pseudonym
*/
if(!defined('CMS'))die;
global$Eleanor, $mainpage, $title;
$Eleanor->module['config'] = include($Eleanor->module['path']. 'config.php');
Eleanor::$Template->queue[] = $Eleanor->module['config']['admintpl'];

$lang = Eleanor::$Language->Load($Eleanor->module['path'] .'lang_admin-*.php', $GLOBALS['Eleanor']->module['config']['n']);
Eleanor::LoadOptions($Eleanor->module['config']['opts'],false);

$mainpage = false;

$R = Eleanor::$Db->Query('SELECT COUNT(`status`) FROM `'.P.'question` WHERE `status`=-1');
list($cnt) = $R->fetch_row();

$Eleanor->Categories=new Categories_manager;
$Eleanor->Categories->table = $Eleanor->module['config']['c'];
$Eleanor->Categories->deletecb='DelCategories';

$Eleanor->module['links']=array(
	'list'=>$Eleanor->Url->Prefix(),

	'add'=>$Eleanor->Url->Construct(array('do'=>'add')),
	'options'=>$Eleanor->Url->Construct(array('do'=>'options')),
	'categories'=>$Eleanor->Url->Construct(array('do'=>'categories')),
	//'addf'=>$Eleanor->Url->Construct(array('do'=>'addf'),
);

$Eleanor->navigation=array(
	array($Eleanor->Url->Prefix(true),$lang['list'],'act'=>&$mainpage,
		'submenu'=>array(
			$cnt>0 ? array($Eleanor->Url->Construct(array('filter'=>1,'fistatus'=>-1)),sprintf($lang['new_question'],$cnt),'act'=>isset($_GET['fistatus']) and $_GET['fistatus']==-1) : false,
			array($Eleanor->Url->Construct(array('do'=>'add')),$lang['add'],'act'=>isset($_GET['do']) and $_GET['do']=='add'),
		),
	),
	array($Eleanor->Url->Construct(array('do'=>'options')),Eleanor::$Language['main']['options'],'act'=>isset($_GET['do']) and $_GET['do']=='options' and !isset($_GET['event'])),
	array($Eleanor->Url->Construct(array('do'=>'categories')),$lang['cats_manage']),
);

$Eleanor->post=false;
$Eleanor->ct=array(
	'language'=>Eleanor::$vars['multilang'] ? array(
		'title'=>$lang['language'],
		'descr'=>'',
		'type'=>'select',
		'bypost'=>&$Eleanor->post,
		'options'=>array(
			'callback'=>'GetLanguages',
			'addon'=>array(
				'tabindex'=>1
			),
		),
	) : null,
	'name'=>array(
		'title'=>$lang['tname'],
		'descr'=>'',
		'type'=>'edit',
		'bypost'=>&$Eleanor->post,
		'options'=>array(
			'htmlsafe'=>true,
			'addon'=>array(
				'tabindex'=>2
			),
		),
	),
);

if(isset($_GET['do']))
	switch($_GET['do'])
	{
		case'add':
			if($_SERVER['REQUEST_METHOD']=='POST' and Eleanor::$our_query)
				Save(0);
			else
				AddEdit(0);
		break;
		case'categories':
			$Eleanor->Url->SetPrefix(array('do'=>'categories'),true);
			$c=$Eleanor->Categories->Show();
			if($c) {
				$c=Eleanor::$Template->Categories($c);
				Start();
				echo$c;
			}
		break;
		case'options':
			$Eleanor->Url->SetPrefix(array('do'=>'options'),true);
			$c=$Eleanor->Settings->GetInterface('group',$Eleanor->module['config']['opts']);
			Start();
			echo$c;
		break;
		default:
			ShowQuestion();
	}
elseif(isset($_GET['edit']))
{
	$id=(int)$_GET['edit'];
	if($_SERVER['REQUEST_METHOD']=='POST' and Eleanor::$our_query)
		Save($id);
	else
		AddEdit($id);
}
elseif(isset($_GET['delete']))
{
	$id=(int)$_GET['delete'];
	if(!Eleanor::$our_query)
		return GoAway();
	$R = Eleanor::$Db->Query('SELECT `id`,`title` FROM `'.$Eleanor->module['config']['t'].'` WHERE `id`='.$id.' AND `language` IN (\'\',\''.Language::$main.'\') LIMIT 1');
	if(!$arr=$R->fetch_assoc())
		return GoAway(true);
	if(isset($_POST['ok'])) {
		Files::Delete(Eleanor::$root.Eleanor::$uploads.DIRECTORY_SEPARATOR.$Eleanor->module['config']['n'].DIRECTORY_SEPARATOR.$id);
		Eleanor::$Db->Delete(P.'comments','`module`='.$Eleanor->module['id'].' AND `contid`'.Eleanor::$Db->In($_POST['mass']));
		Eleanor::$Db->Delete($Eleanor->module['config']['t'],'`id`='.$id.' LIMIT 1');
		Eleanor::$Db->Delete($Eleanor->module['config']['tl'],'`id`='.$id);
		Eleanor::$Db->Delete($Eleanor->module['config']['nt'],'`question`='.$id);
		Eleanor::$Cache->Lib->DeleteByTag($Eleanor->module['config']['n']);
		return GoAway(empty($_POST['back']) ? true : $_POST['back']);
	}
	$title=Eleanor::$Language[$Eleanor->module['config']['n']]['del_confirm'];
	if(isset($_GET['noback']))
		$back='';
	else
		$back=isset($_POST['back']) ? (string)$_POST['back'] : getenv('HTTP_REFERER');
	$c=Eleanor::$Template->Cover(Eleanor::$Template->Confirm(sprintf(Eleanor::$Language[$Eleanor->module['config']['n']]['submit_del'],$arr['title']),$back));
	Start();
	echo$c;
} elseif(isset($_GET['swap'])) {
	$id=(int)$_GET['swap'];
	if(Eleanor::$our_query) {
		$R = Eleanor::$Db->Query('SELECT `pinned`,`status` FROM `'.$Eleanor->module['config']['t'].'` WHERE `id`='.$id.' LIMIT 1');
		if(list($pin,$st)=$R->fetch_row())
		{
			if($st<=0)
			{
				if($pin)
					Eleanor::$Db->Update($Eleanor->module['config']['t'],array('!status'=>'IF(`date`>`pinned` AND `date`<=NOW(),1,2)'),'`id`='.$id.' LIMIT 1');
				else
					Eleanor::$Db->Update($Eleanor->module['config']['t'],array('status'=>1),'`id`='.$id.' LIMIT 1');
			}
			else
			{
				Eleanor::$Db->Update($Eleanor->module['config']['t'],array('status'=>0),'`id`='.$id.' LIMIT 1');
			}
		}
		$R = Eleanor::$Db->Query('UPDATE `'.$Eleanor->module['config']['t'].'` INNER JOIN `'.$Eleanor->module['config']['tl'].'` USING(`id`) SET `lstatus`=`status` WHERE `id`='.$id);
		Eleanor::$Cache->Lib->DeleteByTag($Eleanor->module['config']['n']);
	}
	$back=getenv('HTTP_REFERER');
	GoAway($back ? $back.'#it'.$id : true);
} else
	ShowQuestion();

function ShowQuestion()
{
	global$Eleanor,$title;
	$title=Eleanor::$Language[$Eleanor->module['config']['n']]['list'];
	$page=isset($_GET['page']) ? (int)$_GET['page'] : 1;
	$qs=$items=array();
	$where='';
	if(isset($_REQUEST['fi']) and is_array($_REQUEST['fi'])) {
		if($_SERVER['REQUEST_METHOD']=='POST')
			$page=1;
		$qs['']['fi']=array();
		if(isset($_REQUEST['fi']['title'],$_REQUEST['fi']['titlet']) and $_REQUEST['fi']['title']!='') {
			$t = Eleanor::$Db->Escape((string)$_REQUEST['fi']['title'],false);
			switch($_REQUEST['fi']['titlet']) {
				case'b':
					$t=' LIKE \''.$t.'%\'';
					break;
				case'm':
					$t=' LIKE \'%'.$t.'%\'';
					break;
				case'e':
					$t=' LIKE \'%'.$t.'\'';
					break;
				default:
					$t='=\''.$t.'\'';
			}
			$qs['']['fi']['title'] = $_REQUEST['fi']['title'];
			$qs['']['fi']['titlet'] = $_REQUEST['fi']['titlet'];
			$where.=' AND `title`'.$t;
		}
		if(!empty($_REQUEST['fi']['category']))
			if($_REQUEST['fi']['category']=='no')
			{
				$qs['']['fi']['category']='';
				$where.=' AND `cats`=\'\'';
			}
			else
			{
				$qs['']['fi']['category']=(int)$_REQUEST['fi']['category'];
				$where.=' AND `cats` LIKE \'%,'.$qs['']['fi']['category'].',%\'';
			}
		if(isset($_REQUEST['fi']['status']) and $_REQUEST['fi']['status']!='-') {
			$qs['']['fi']['status']=(int)$_REQUEST['fi']['status'];
			$where.=$qs['']['fi']['status']==1 ? ' AND `status`IN(1,2)' : ' AND `status`='.$qs['']['fi']['status'];
		}
	}

	if(Eleanor::$our_query and isset($_POST['op'],$_POST['mass']))
		do
		{
			$in=Eleanor::$Db->In($_POST['mass']);
			switch($_POST['op']) {
				case'd':
					Eleanor::$Db->Update($Eleanor->module['config']['t'],array('status'=>0),'`id`'.$in);
					break;
				case'a':
					Eleanor::$Db->Update($Eleanor->module['config']['t'], array('status' => 1), '`id`'. $in);
					break;
				case'm':
					Eleanor::$Db->Update($Eleanor->module['config']['t'],array('status'=>-1),'`id`'.$in);
					break;
				case'k':
					Eleanor::$Db->Delete(P.'comments','`module`='.$Eleanor->module['id'].' AND `contid`'.Eleanor::$Db->In($_POST['mass']));
					Eleanor::$Db->Delete($Eleanor->module['config']['t'],'`id`'.$in);
					Eleanor::$Db->Delete($Eleanor->module['config']['tl'],'`id`'.$in);
					Eleanor::$Cache->Lib->DeleteByTag($Eleanor->module['config']['n']);
					break 2;
			}
			Eleanor::$Cache->Lib->DeleteByTag($Eleanor->module['config']['n']);
		}while(false);

	$R=Eleanor::$Db->Query('SELECT COUNT(`id`) FROM `'.$Eleanor->module['config']['t'].'` INNER JOIN `'.$Eleanor->module['config']['tl'].'` USING(`id`) WHERE `language` IN (\'\',\''.Language::$main.'\')'.$where);
	list($cnt)=$R->fetch_row();
	if($page<=0)
		$page=1;
	if(isset($_GET['new-pp']) and 4<$pp=(int)$_GET['new-pp'])
		Eleanor::SetCookie('per-page',$pp);
	else
		$pp=abs((int)Eleanor::GetCookie('per-page'));
	if($pp<5 or $pp>500)
		$pp=50;
	$offset=abs(($page-1)*$pp);
	if($cnt and $offset>=$cnt)
		$offset=max(0,$cnt-$pp);
	$sort=isset($_GET['sort']) ? $_GET['sort'] : '';
	if(!in_array($sort,array('id','title','date','author','status')))
		$sort='';
	$so=$_SERVER['REQUEST_METHOD']!='POST' && $sort && isset($_GET['so']) ? $_GET['so'] : 'desc';
	if($so!='asc')
		$so='desc';
	if($sort and ($sort!='id' or $so!='asc'))
		$qs+=array('sort'=>$sort,'so'=>$so);
	else
		$sort='date';
	$qs+=array('sort'=>false,'so'=>false);

	if ($cnt > 0) {
		$t=time();
		$R=Eleanor::$Db->Query('SELECT `id`,`cats`,`date`,`pinned`,`date`>`pinned` `_pinned`,`author`,`author_id`,`status`,`title` FROM `'.$Eleanor->module['config']['t'].'` INNER JOIN `'.$Eleanor->module['config']['tl'].'` USING(`id`) WHERE `language` IN (\'\',\''.Language::$main.'\')'.$where.' ORDER BY `'.$sort.'` '.$so.' LIMIT '.$offset.', '.$pp);
		while($a=$R->fetch_assoc())
		{
			$a['cats'] = $a['cats'] ? array_unique(explode(',,',trim($a['cats'],','))) : array();
			$a['_aedit'] = $Eleanor->Url->Construct(array('edit'=>$a['id']));
			$a['_adel'] = $Eleanor->Url->Construct(array('delete'=>$a['id']));
			$a['_aswap'] = $Eleanor->Url->Construct(array('swap'=>$a['id']));

			if((int)$a['pinned'] && $a['_pinned'])
				$a['date']=$a['pinned'];
			unset($a['pinned']);

			$items[$a['id']]=array_slice($a,1);
		}
	}
	$Eleanor->Categories->Init($Eleanor->module['config']['c']);
	$links=array(
		'sort_id'=>$Eleanor->Url->Construct(array_merge($qs,array('sort'=>'id','so'=>$qs['sort']=='id' && $qs['so']=='asc' ? 'desc' : 'asc'))),
		'sort_title'=>$Eleanor->Url->Construct(array_merge($qs,array('sort'=>'title','so'=>$qs['sort']=='title' && $qs['so']=='asc' ? 'desc' : 'asc'))),
		'sort_date'=>$Eleanor->Url->Construct(array_merge($qs,array('sort'=>'date','so'=>$qs['sort']=='date' && $qs['so']=='asc' ? 'desc' : 'asc'))),
		'sort_author'=>$Eleanor->Url->Construct(array_merge($qs,array('sort'=>'author','so'=>$qs['sort']=='author' && $qs['so']=='asc' ? 'desc' : 'asc'))),
		'form_items'=>$Eleanor->Url->Construct($qs+array('page'=>$page>1 ? $page : false)),
		'pp'=>function($n)use($qs){ return$GLOBALS['Eleanor']->Url->Construct($qs+array('new-pp'=>$n)); },
		'first_page'=>$Eleanor->Url->Construct($qs),
		'pages'=>function($n)use($qs){ return$GLOBALS['Eleanor']->Url->Construct($qs+array('page'=>$n)); },
	);
	$c=Eleanor::$Template->QuestionList($items,$Eleanor->Categories->dump,$cnt,$pp,$qs,$page,$links);
	Start();
	echo$c;
}

function AddEdit($id,$error='')
{global$Eleanor,$title;
	if($id) {
		$title[]=Eleanor::$Language[$Eleanor->module['config']['n']]['editing'];
		$R = Eleanor::$Db->Query('SELECT '.($error ? '`voting`' : '*,`date`>`pinned` `_pin`').' FROM `'.$Eleanor->module['config']['t'].'` WHERE id='.$id.' LIMIT 1');
		if(!$values=$R->fetch_assoc())
			return GoAway(true);

		$values['_ping']=$values['status']!=1;

		if(!$error)
		{
			$values['cats']=$values['cats'] ? explode(',,',trim($values['cats'],',')) : array();

			#Служебное
			$values['_maincat']=reset($values['cats']);
			if($values['status']==2)
				$values['status']=1;
			if($values['_pin'] and $values['pinned'])
				list($values['pinned'],$values['date'])=array($values['date'],$values['pinned']);

			$R = Eleanor::$Db->Query('SELECT `language`,`uri`,`title`,`text` FROM `'.$Eleanor->module['config']['tl'].'` WHERE `id`='.$id);
			while($temp=$R->fetch_assoc())
				if(!Eleanor::$vars['multilang'] and (!$temp['language'] or $temp['language']==Language::$main))
				{
					foreach(array_slice($temp,1) as $tk=>$tv)
						$values[$tk]=$tv;
					if(!$temp['language'])
						break;
				}
				elseif(!$temp['language'] and Eleanor::$vars['multilang'])
				{
					foreach(array_slice($temp,1) as $tk=>$tv)
						$values[$tk][Language::$main]=$tv;
					$values['one_lang']=true;
					break;
				}
				elseif(Eleanor::$vars['multilang'] and isset(Eleanor::$langs[$temp['language']]))
					foreach(array_slice($temp,1) as $tk=>$tv)
						$values[$tk][$temp['language']]=$tv;

			if(Eleanor::$vars['multilang'])
			{
				$values['one_lang']=(!is_array($values['title']) or count($values['title'])==1 and isset($values['title'][LANGUAGE]));
				foreach(Eleanor::$langs as $k=>&$v)
					if(!isset($values['title'][$k]))
						$values['title'][$k]=$values['text'][$k]=$values['uri'][$k]='';
			}
		}
	} else {
		$dv=Eleanor::$vars['multilang'] ? array(''=>'') : '';
		$values=array(
			'cats'=>array(),
			'date'=>date('Y-m-d H:i:s'),
			'pinned'=>'',
			'author'=>Eleanor::$Login->GetUserValue('name',false),
			'author_id'=>Eleanor::$Login->GetUserValue('id'),
			'show_detail'=>true,
			'show_sokr'=>false,
			'reads'=>0,
			'status'=>1,
			#Языковые
			'title'=>$dv,
			'text'=>$dv,
			'uri'=>$dv,
			#Специальные
			'one_lang'=>true,
			'_maincat'=>0,
		);
		$title[]=Eleanor::$Language[$Eleanor->module['config']['n']]['adding'];
	}
	if($error) {
		$bypost=true;
		if($error===true)
			$error='';
		if(Eleanor::$vars['multilang'])
		{
			$values['meta_title']=isset($_POST['meta_title']) ? (array)$_POST['meta_title'] : array();
			$values['meta_descr']=isset($_POST['meta_descr']) ? (array)$_POST['meta_descr'] : array();
			$values['title']=isset($_POST['title']) ? (array)$_POST['title'] : array();
			$values['text']=isset($_POST['text']) ? (array)$_POST['text'] : array();
			$values['uri']=isset($_POST['uri']) ? (array)$_POST['uri'] : array();
			$values['one_lang']=isset($_POST['one_lang']);
		}
		else
		{
			$values['meta_title']=isset($_POST['meta_title']) ? (string)$_POST['meta_title'] : '';
			$values['meta_descr']=isset($_POST['meta_descr']) ? (string)$_POST['meta_descr'] : '';
			$values['title']=isset($_POST['title']) ? (string)$_POST['title'] : '';
			$values['text']=isset($_POST['text']) ? (string)$_POST['text'] : '';
			$values['uri']=isset($_POST['uri']) ? (string)$_POST['uri'] : '';
		}
		$values['_maincat']=isset($_POST['_maincat']) ? (int)$_POST['_maincat'] : 0;
		$values['cats']=isset($_POST['cats']) ? (array)$_POST['cats'] : array();
		$values['date']=isset($_POST['date']) ? (string)$_POST['date'] : date('Y-m-d H:i:s');
		$values['pinned']=isset($_POST['pinned']) ? (string)$_POST['pinned'] : '';
		$values['author']=isset($_POST['author']) ? (string)$_POST['author'] : '';
		$values['author_id']=isset($_POST['author_id']) ? (string)$_POST['author_id'] : '';
		$values['reads']=isset($_POST['reads']) ? (int)$_POST['reads'] : '';
		$values['status']=isset($_POST['status']) ? (int)$_POST['status'] : '';
		$values['show_detail']=isset($_POST['show_detail']);
		$values['show_sokr']=isset($_POST['show_sokr']);
		$values['_ping']=isset($_POST['_ping']) && $values['status']==1;
	}
	else
		$bypost=false;

	$Eleanor->Categories->Init($Eleanor->module['config']['c']);
	$c = Eleanor::$Template->AddEdit($id,$values,$error,$bypost);
	Start();
	echo$c;
}

function Save($id)
{global$Eleanor;
	#Перечень переменных, которые дублируются для языковой таблицы ниже
	$maincat=isset($_POST['_maincat']) ? (int)$_POST['_maincat'] : false;
	$cats=isset($_POST['cats']) ? array_unique((array)$_POST['cats']) : array();
	if($cats and count($cats)>1)
	{
		sort($cats,SORT_NUMERIC);
		if($maincat!=$cats[0])
			array_unshift($cats,$maincat ? $maincat : reset($cats));
	}
	$cats=$cats ? ','.join(',,',$cats).',' : '';

	if(Eleanor::$vars['multilang'] and !isset($_POST['one_lang']))
	{
		$langs=(empty($_POST['lang']) or !is_array($_POST['lang'])) ? array() : $_POST['lang'];
		$langs=array_intersect(array_keys(Eleanor::$langs),$langs);
		if(!$langs)
			$langs=array(Language::$main);
	}
	else
		$langs=array('');

	$values=array(
		'cats'=>$cats,
		'date'=>isset($_POST['date']) ? (string)$_POST['date'] : date('Y-m-d H:i:s'),
		'pinned'=>isset($_POST['pinned']) ? (string)$_POST['pinned'] : null,
		'author'=>isset($_POST['author']) ? (string)$_POST['author'] : '',
		'author_id'=>isset($_POST['author_id']) ? (string)$_POST['author_id'] : 0,
		'reads'=>isset($_POST['reads']) ? (int)$_POST['reads'] : '',
		'status'=>isset($_POST['status']) ? (int)$_POST['status'] : '',
		'show_detail'=>isset($_POST['show_detail']),
		'show_sokr'=>isset($_POST['show_sokr']),
	);
	if($da=strtotime($values['date']) and $da>time())
		$values['status']=2;

	if($values['author'] and $values['author_id']>0)
	{
		Eleanor::$UsersDb->Query('SELECT `id` FROM `'.USERS_TABLE.'` WHERE `name`=\''.Eleanor::$Db->Escape($values['author'],false).'\' LIMIT 1');
		if(Eleanor::$UsersDb->NumRows()>0)
			list($values['author_id'])=Eleanor::$UsersDb->FetchRow();
		else
			$values['author_id']=0;
	}
	$values['author']=htmlspecialchars($values['author'],ENT_QUOTES,CHARSET,false);

	if($da and $values['pinned'] and $pin=strtotime($values['pinned']))
	{
		if($pin<$da)
			return AddEdit($id,Eleanor::$Language[$Eleanor->module['config']['n']]['error_pinned']);
		elseif($values['status']>=1)
			list($values['date'],$values['pinned'])=array($values['pinned'],$values['date']);
	}
	else
		$values['pinned']=null;

	if(Eleanor::$vars['multilang'])
	{
		$lvalues=array(
			'title'=>array(),
			'text'=>array(),
			'uri'=>array(),
		);
		foreach($langs as $l) {
			$lng=$l ? $l : Language::$main;
			$GLOBALS['Eleanor']->Editor->imgalt=$lvalues['title'][$lng]=(isset($_POST['title'],$_POST['title'][$lng]) and is_array($_POST['title'])) ? (string)Eleanor::$POST['title'][$lng] : '';
			$lvalues['text'][$lng]=isset($_POST['text'],$_POST['text'][$lng]) && is_array($_POST['text']) ? $Eleanor->Editor_result->GetHtml((string)$_POST['text'][$lng],true) : '';
			$lvalues['uri'][$lng]=isset($_POST['uri'],$_POST['uri'][$lng]) && is_array($_POST['uri']) ? (string)$_POST['uri'][$lng] : '';
		}
	}
	else
	{
		$GLOBALS['Eleanor']->Editor->imgalt=isset($_POST['title']) ? (string)Eleanor::$POST['title'] : '';
		$lvalues=array(
			'title'=>array(''=>$GLOBALS['Eleanor']->Editor_result->imgalt),
			'text'=>array(''=>$Eleanor->Editor_result->GetHtml('text')),
			'uri'=>array(''=>isset($_POST['uri']) ? (string)$_POST['uri'] : ''),
			'meta_title'=>array(''=>isset($_POST['meta_title']) ? (string)Eleanor::$POST['meta_title'] : ''),
			'meta_descr'=>array(''=>isset($_POST['meta_descr']) ? (string)Eleanor::$POST['meta_descr'] : ''),
		);
	}
	$ml=in_array('',$langs) ? Language::$main : '';
	foreach(array('title','text') as $field)
		foreach($lvalues[$field] as $k => $v)
			if(!$v and (in_array($k,$langs) or $ml==$k))
				return AddEdit($id,Eleanor::$Language[$Eleanor->module['config']['n']]['empty_'.$field]);

//	foreach($lvalues['uri'] as $k => $v) {
//		if($v=='')
//			$v=htmlspecialchars_decode($lvalues['title'][$k],ENT_QUOTES);
//		$v=$Eleanor->Url->Filter($v,$k);
//		$R = Eleanor::$Db->Query('SELECT `id` FROM `'.$Eleanor->module['config']['t'].'` INNER JOIN `'.$Eleanor->module['config']['tl'].'` USING(`id`) WHERE `uri`={0} AND `language`'.($k ? 'IN(\'\',\''.$k.'\')' : '=\'\'').($id ? ' AND `id`!='.$id : '').' LIMIT 1', array($v));
//		if($R->num_row > 0)
//			$v=null;
//	}

	$date=$values['date'];
	$status=$values['status'];
	$ping=false;
	if($id) {
		Eleanor::$Db->Update($Eleanor->module['config']['t'],$values,'id='.$id.' LIMIT 1');
		Eleanor::$Db->Delete($Eleanor->module['config']['tl'],'`id`='.$id.' AND `language`'.Eleanor::$Db->In($langs,true));
		foreach($langs as $v) {
			if(Eleanor::$vars['multilang']) {
				$lang=$v ? $v : Language::$main;
				$values=array(
					'id'=>$id,
					'language'=>$v,
					'uri'=>$lvalues['uri'][$lang],
					'title'=>$lvalues['title'][$lang],
					'text'=>$lvalues['text'][$lang],
					'last_mod'=>date('Y-m-d H:i:s'),
				);
			}
			else
				$values=array(
					'id'=>$id,
					'language'=>'',
					'uri'=>$lvalues['uri'][''],
					'title'=>$lvalues['title'][''],
					'text'=>$lvalues['text'][''],
					'last_mod'=>date('Y-m-d H:i:s'),
				);
			$values['lstatus']=$status;
			$values['ldate']=$date;
			$values['lcats']=$cats;
			Eleanor::$Db->Replace($Eleanor->module['config']['tl'],$values);
		}
	} else {
		if($status==1) {
			$ping=true;
		}
		$id=Eleanor::$Db->Insert($Eleanor->module['config']['t'],$values);
		$values=array('id'=>array(),'language'=>array(),'uri'=>array(),'title'=>array(),'text'=>array(),'meta_title'=>array(),'meta_descr'=>array());
		foreach($langs as $v) {
			$values['id'][]=$id;
			$values['last_mod'][]=date('Y-m-d H:i:s');
			$values['lstatus'][]=$status;
			$values['ldate'][]=$date;
			$values['lcats'][]=$cats;
			if(Eleanor::$vars['multilang']) {
				$lang=$v ? $v : Language::$main;
				$values['language'][]=$v;
				$values['uri'][]=$lvalues['uri'][$lang];
				$values['title'][]=str_replace($ft['from'],$ft['to'],$lvalues['title'][$lang]);
				$values['text'][]=str_replace($ft['from'],$ft['to'],$lvalues['text'][$lang]);
			} else {
				$values['language'][]='';
				$values['uri'][]=$lvalues['uri'][''];
				$values['title'][]=str_replace($ft['from'],$ft['to'],$lvalues['title']['']);
				$values['text'][]=str_replace($ft['from'],$ft['to'],$lvalues['text']['']);
				break;
			}
		}

		Eleanor::$Db->Insert($Eleanor->module['config']['tl'], $values);
	}
	Eleanor::$Cache->Obsolete($Eleanor->module['config']['n'] .'_nextrun');
	Eleanor::$Cache->Lib->DeleteByTag($Eleanor->module['config']['n']);
	if($ping and Eleanor::$vars['publ_ping']) {
		$Eleanor->Url->furl = Eleanor::$vars['furi'];
		$Eleanor->Url->file = Eleanor::$services['user']['file'];
		$sd=PROTOCOL . Eleanor::$domain . Eleanor::$site_path;
		Ping::Add(array('id'=>$Eleanor->module['config']['n'],'changes'=>$sd . $Eleanor->Url->Prefix(),'rss'=>$sd.Eleanor::$services['rss']['file'].'?'.Url::Query(Eleanor::$vars['multilang'] && Language::$main!=LANGUAGE ? array('lang'=>Eleanor::$langs[Language::$main]['uri'],'module'=>$Eleanor->module['name']) : array('module'=>$Eleanor->module['name']))));
	}
	GoAway(empty($_POST['back']) ? true : $_POST['back']);
}

#Служебное
function GetLanguages($arr)
{global$Eleanor;
	$sel=Eleanor::Option(Eleanor::$Language[$Eleanor->module['config']['n']]['forallt'],'',in_array('',$arr['value']));
	foreach(Eleanor::$langs as $k=>&$v)
		$sel.=Eleanor::Option($v['name'],$k,in_array($k,$arr['value']));
	return$sel;
}

function DelCategories($ids)
{global$Eleanor;
	#К сожалению в MySQL не предусмотрена функция замены по регулярному выражению. Расставляем грабли.
	foreach($ids as &$v)
	{
		Eleanor::$Db->Update($Eleanor->module['config']['t'],array('!cats'=>'REPLACE(`cats`,\','.$v.',\',\'\')'));
		Eleanor::$Db->Update($Eleanor->module['config']['tl'],array('!lcats'=>'REPLACE(`lcats`,\','.$v.',\',\'\')'));
	}
	Eleanor::$Cache->Lib->DeleteByTag($Eleanor->module['config']['n']);
}
?>